#include "mycoin.h"
#include <QPixmap>
#include <QString>
#include <QMessageBox>
#include <QDebug>
//#include <QSound>

MyCoin::MyCoin(QString Imgpath)
{
    //定义金币图案
    QPixmap pix;
    bool ret = pix.load(Imgpath);
    if(!ret)
    {
        QString str = QString("加载 %1 资源失败！").arg(Imgpath);//金币图片加载失败时的提示
            QMessageBox::warning(this, "消息提示", str);
        return;
    }

    this->setFixedSize(pix.width(),pix.height());
    this->setStyleSheet("QPushButton{border:0px;}");
    this->setIcon(pix);
    this->setIconSize(QSize(pix.width(),pix.height()));

    //初始化定时器
    timer1 = new QTimer(this);
    timer2 = new QTimer(this);

    //监听 正->反 定时器信号
    connect(timer1, &QTimer::timeout, this, [=](){
        QPixmap pix;
        QString strPath = QString(":/resource/image/Coin000%1.png").arg(this->min++);
        bool ret = pix.load(strPath);
        if(!ret)
        {
            QString str = QString("加载 %1 资源失败！").arg(Imgpath);
                QMessageBox::warning(this, "消息提示", str);
            return;
        }
        this->setFixedSize(pix.width(),pix.height());
        this->setStyleSheet("QPushButton{border:0px;}");
        this->setIcon(pix);
        this->setIconSize(QSize(pix.width(),pix.height()));
        //如果翻转完毕
        if(this->min > this->max)
        {
            this->min = 1;
            timer1->stop();
            isFlipping = false;  //翻转完成
        }
    });

    //监听 反->正 定时器信号
    connect(timer2, &QTimer::timeout, this, [=](){
        QPixmap pix;
        QString strPath = QString(":/resource/image/Coin000%1.png").arg(this->max--);
        bool ret = pix.load(strPath);
        if(!ret)
        {
            QString str = QString("加载 %1 资源失败！").arg(Imgpath);
                QMessageBox::warning(this, "消息提示", str);
            return;
        }
        this->setFixedSize(pix.width(),pix.height());
        this->setStyleSheet("QPushButton{border:0px;}");
        this->setIcon(pix);
        this->setIconSize(QSize(pix.width(),pix.height()));
        //如果翻转完毕
        if(this->max < this->min)
        {
            this->max = 8;
            timer2->stop();
            isFlipping = false; //翻转完成
        }
    });
}

void MyCoin::changeFlag()
{
    isFlipping = true; //设置动作标志位

    if (true == this->flag)
    {
        this->timer1->start(30);  //开始计时, 一旦开始计时，定时器将反复计时，直到执行 Qtimer->stop()函数
        this->flag = false;     //标志变量翻转
    }
    else
    {
        this->timer2->start(30);  //开始计时, 一旦开始计时，定时器将反复计时，直到执行 Qtimer->stop()函数
        this->flag = true;     //标志变量翻转
    }
}

//鼠标按下事件
void MyCoin::mousePressEvent(QMouseEvent *ev)
{
    if ((true == isFlipping) || (true == isCoinWin))//正在执行翻转或胜利后，不处理鼠标事件
    {
        return;
    }
    else
    {
        return QPushButton::mousePressEvent(ev);
    }
}

